package com.chinawayltd.ews.sample.web.algorithm;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TDriverPlan;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.algorithm.DriverPlanVO;
import com.chinawayltd.ews.sample.model.algorithm.DriverWorkVO;
import com.chinawayltd.ews.sample.service.algorithm.DriverPlanService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.service.task.TaskService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.DriverGirdQuery;
import com.chinawayltd.ews.sample.web.query.DriverPlanGirdQuery;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 司机排班管理
 * @author: chenxin
 * @create: 2018年4月11日 下午5:28:36
 */
@Api(tags = { "司机排班管理API" })
@RestController
@RequestMapping(value = "/web/driver")
public class DriverPlanController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	DriverPlanService driverPlanService;
    @Autowired
    private TaskService taskService;
	@Autowired
	private CommonService commonService;
	private final String tableName = "T_DRIVER_PLAN";

	@ApiOperation(value = "列表查询接口")
	@RequestMapping(value = "/plan/loadGirdData", method = { RequestMethod.POST })
	public ResultModel loadGirdData(DriverPlanGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			List<DriverPlanVO> list = driverPlanService.listDriverPlanByPage(queryParam);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", list));
			model.setPage(queryParam);
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询发生异常"));
			logger.error("查询司机排班发生异常！" + e);
		}
		return model;
	}

	@ApiOperation(value = "查询所有数据接口")
	@RequestMapping(value = "/plan/listAll", method = { RequestMethod.POST })
	public List<TDriverPlan> listAll() {
		List<TDriverPlan> list = null;
		try {
			list = driverPlanService.listAll();
		} catch (Exception e) {
			logger.error("查询所有数据发生异常！" + e);
		}
		return list;
	}

	@ApiOperation(value = "司机排班信息根据ID查询接口")
	@RequestMapping(value = "/plan/find/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "司机排班ID", dataType = "Long", required = true)
	public ResultModel getById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			TDriverPlan data = driverPlanService.getById(id);
			model.setData(new JSONObject().fluentPut("result", data));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
			logger.error("根据ID查询信息出错！id：" + id, e);
		}
		return model;
	}

	@ApiOperation(value = "司机排班信息新增接口")
	@RequestMapping(value = "/plan/add", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "carId", value = "车辆ID", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "driverId", value = "司机ID", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "shiftId", value = "班次ID", dataType = "Long", required = true) })
	public ResultModel add(TDriverPlan tDriverPlan) {
		ResultModel model = new ResultModel();
		try {
			if (StringUtils.isBlank(tDriverPlan.getShiftId().toString())) {
				throw new BusinessException("班次不能为空，添加失败");
			}
			if (StringUtils.isBlank(tDriverPlan.getDriverId().toString())) {
				throw new BusinessException("司机不能为空，添加失败");
			}
			// 判断是否冲突
			boolean flag = driverPlanService.judgeDriverShiftConflict(tDriverPlan);
			if (flag) {
				throw new BusinessException("司机排班时间冲突，添加失败");
			}
			int result = driverPlanService.add(tDriverPlan);
			if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
	        }
		}catch(BusinessException e){
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		}catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "司机排班信息添加失败"));
			logger.error("司机排班信息新增发生异常", e);
		}
		return model;
	}
	
	@ApiOperation(value = "司机排班信息修改接口")
	@RequestMapping(value = "/plan/update", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "id", value = "司机排班信息id", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "carId", value = "车辆ID", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "driverId", value = "司机ID", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "shiftId", value = "班次ID", dataType = "Long", required = true) })
	public ResultModel update(TDriverPlan tDriverPlan) {
		ResultModel model = new ResultModel();
		try {
			
			if (StringUtils.isBlank(tDriverPlan.getId().toString())) {
				throw new BusinessException("数据为空，修改失败");
			}
			if (StringUtils.isBlank(tDriverPlan.getShiftId().toString())) {
				throw new BusinessException("班次不能为空，修改失败");
			}
			if (StringUtils.isBlank(tDriverPlan.getDriverId().toString())) {
				throw new BusinessException("司机不能为空，修改失败");
			}
			// 判断是否冲突
			boolean flag = driverPlanService.judgeDriverShiftConflict(tDriverPlan);
			if (flag) {
				throw new BusinessException("司机排班时间冲突，修改失败");
			}
			int result = driverPlanService.update(tDriverPlan);
			if (result > 0) {
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
			} else {
				model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			}
		} catch(BusinessException e){
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "司机排班信息添加失败"));
			logger.error("司机排班信息修改发生异常！" + e);
		}
		return model;
	}

	@ApiOperation(value = "司机排班信息删除接口")
	@RequestMapping(value = "/plan/delete/{id}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "id", value = "司机排班信息ID", dataType = "Long", required = true)
	public ResultModel delete(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			int result = driverPlanService.delete(id);
			if (result > 0){
				model.setData(new JSONObject().fluentPut("result", "删除成功"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
			logger.error("根据ID删除信息出错！id：" + id, e);
		}
		return model;
	}

	@ApiOperation(value = "通过ID查询操作日记接口")
	@RequestMapping(value = "/plan/getLogDataById", method = { RequestMethod.POST })
	public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName(tableName);
			List<TLog> list = commonService.getLogDataById(queryParam);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", list));
			model.setPage(queryParam);
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
			logger.error("通过ID查询操作日记接口异常！", e);
		}
		return model;
	}

	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/plan/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		// 1.分割ids
		String[] idArr = ids.split(",");
		int result = driverPlanService.deletesByIds(idArr);
		if (result > 0){
			model.setData(new JSONObject().fluentPut("result", "删除成功"));
		}else{
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
		}
		return model;
	}

	@ApiOperation(value = "批量修改班次接口")
	@RequestMapping(value = "/plan/updateAllShift", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "ids", value = "拼接需要修改的司机排班id串如：1,2,3", dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "shiftId", value = "班次ID", dataType = "Long") })
	public ResultModel updateAllShift(String ids, Long shiftId) {
		
		if (StringUtils.isBlank(ids)) {
			return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg", "更改失败，请先选择司机排班信息！"));
		}
		ResultModel model = new ResultModel();
		try {
			String[] idArr = ids.split(",");
			int old = idArr.length;
			int nee = 0;
			for (String string : idArr) {
				Long id = Long.parseLong(string);
				TDriverPlan tDriverPlan = driverPlanService.getById(id);
				tDriverPlan.setShiftId(shiftId);
				boolean flag = driverPlanService.judgeDriverShiftConflict(tDriverPlan);
				if (!flag) {
					driverPlanService.update(tDriverPlan);
					nee++;
				} else {
					continue;
				}
			}
			model.setCode(0);
			model.setSub_code(0);
			if(nee ==old){
				model.setData(new JSONObject().fluentPut("result", "全部更改成功！"));
			}else if(nee>0 && nee<old){
				model.setData(new JSONObject().fluentPut("result", "成功更改"+nee+"条,其他班次已存在，无法更改！"));
			}else{
				model.setData(new JSONObject().fluentPut("result", "更改失败，班次已存在！"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "更改失败！"));
		}
		return model;
	}

	@ApiOperation(value = "司机排班管理导出接口")
	@RequestMapping(value = "/plan/exportGirdData", method = { RequestMethod.POST })
	public void exportTaskAndOrderDetailGirdData(@RequestBody DriverPlanGirdQuery queryParam,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			List<DriverPlanVO> branchList = driverPlanService.listDriverPlanByPage(queryParam);
			ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(branchList)
					.cloumnList(queryParam.getCloums()).build();
			Workbook workbook = ExcelUtils.generateExcel(excelModel);
			this.sendWorkbook(workbook, "司机排班管理列表", request, response);
		} catch (Exception e) {
			logger.error("司机排班管理列表导出出错！", e);
		}
	}
	
	@ApiOperation(value = "通过司机id查询对象司机排班信息,可用来校验司机唯一性", notes = "添加校验名称不需要ID,修改校验名称必要ID,返回Sub_code=0为可用,1为已存在!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "增加不需要传值，修改的时候需要传id", dataType = "String"),
		@ApiImplicitParam(paramType = "query", name = "name", value = "需要校验的司机id", dataType = "String")})
	@RequestMapping(value = { "/plan/getByIdAndName" }, method = RequestMethod.POST)
	public ResultModel getByIdAndName(String id, String name){
		ResultModel model = new ResultModel();
		try {
			List<TDriverPlan> list = driverPlanService.getByIdAndName(id, name);
			if(list.size() > 0){
				model.setData(new JSONObject().fluentPut("result", "已存在"));
			}else{
				model.setData(new JSONObject().fluentPut("result", "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
		}
		return model;
	}

	/**
	 * 解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * 
	 * @author Fay
	 * @date 2018年5月3日 上午10:07:15
	 * @param file
	 * @param request
	 * @param response
	 */
	@ApiOperation(value = "司机排班信息批量导入")
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/plan/readExcel", method = { RequestMethod.POST })
	public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		JSONObject object = new JSONObject();
		try {
			ExcelObjModel model = ExcelUtils.readExcel(file);
	    	if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = driverPlanService.insertList(list);
			// 3、导出错误数据
			if (result.getList().size() > 0) {
				ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList())
						.cloumnList(result.getCloums()).build();
				Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "司机排班信息", request, response);
			}
		} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
	}

	
    @ApiOperation(value = "司机上班天数统计查询接口")
    @RequestMapping(value = "/work/loadGirdData", method = { RequestMethod.POST })
    public ResultModel driverLoadGirdData(DriverGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
        	List<DriverWorkVO> list = taskService.driverGirdData(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("司机上班天数信息查询接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "司机上班统计信息导出接口")
    @RequestMapping(value = "/work/exportGirdData", method = { RequestMethod.POST })
    public void driverExportGirdData(@RequestBody DriverGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<DriverWorkVO> list = taskService.driverGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list).cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "司机上班统计信息列表" , request, response);
        }catch (Exception e){
            logger.error("司机上班统计信息列表出错！", e);
        }
    }
    @ApiOperation(value = "司机连续上班统计查询接口")
    @RequestMapping(value = "/work/continue/loadGirdData", method = { RequestMethod.POST })
    public ResultModel continueLoadGirdData(DriverGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
        	List<DriverWorkVO> list = driverPlanService.driverContinueWorkGirdData(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("司机连续上班信息查询接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "司机连续上班信息导出接口")
    @RequestMapping(value = "/work/continue/exportGirdData", method = { RequestMethod.POST })
    public void continueDriverExportGirdData(@RequestBody DriverGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
        	List<DriverWorkVO> list = driverPlanService.driverContinueWorkGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list).cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "司机连续上班信息列表" , request, response);
        }catch (Exception e){
            logger.error("司机连续上班信息列表出错！", e);
        }
    }
    
	@ApiOperation(value = "司机连续上班信息消除接口")
	@RequestMapping(value = "/work/continue/update/{id}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "id", value = "司机ID", dataType = "Long", required = true)
	public ResultModel driverExtendUpdate(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			int result = driverPlanService.driverExtendUpdate(id);
			if (result > 0){
				model.setData(new JSONObject().fluentPut("result", "消除成功"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "消除失败"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "消除失败"));
			logger.error("根据ID删除信息出错！id：" + id, e);
		}
		return model;
	}

    
}
